package com.game.fighting.socket;



import org.java_websocket.enums.ReadyState;

import java.net.URI;
import java.util.*;

/**
 * Copyright (C), 2021-2041, chenc 豫R7HQ53
 *
 * @author: chenc
 * Date:     2023/12/5 19:15
 * Description:
 */
public class SocketUtil {
    /**
     * 关闭状态集合
     */
    private static final List<ReadyState> states = new ArrayList<>() {{
        add(ReadyState.CLOSED);
        add(ReadyState.CLOSING);
    }};

    /**
     * 创建socket客户端
     *
     * @param url      连接地址
     * @param interval 每隔多少毫秒 轮询一次 2000 -2秒就可以了
     * @return
     * @throws Exception
     */
    public static SocketClient createSocket(String url, Long interval) throws Exception {
        SocketClient socketClient = new SocketClient(new URI(url));
        socketClient.setReuseAddr(true);
        socketClient.setTcpNoDelay(true);
        while (!socketClient.getReadyState().equals(ReadyState.OPEN)) {
            System.out.println("连接中。。。");
            if (socketClient.getReadyState().equals(ReadyState.NOT_YET_CONNECTED)) {
                socketClient.connect();
            } else if (states.contains(socketClient.getReadyState())) {
                socketClient.reconnect();
            }
            Thread.sleep(interval);
        }
        return socketClient;
    }

    /**
     * 定时任务心跳
     *
     * @param socketClient
     * @param interval
     * @return
     */
    public static Timer heartTimer(SocketClient socketClient, Long interval) {
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if (states.contains(socketClient.getReadyState())) {
                    System.out.println("重连中。。。");
                    socketClient.reconnect();
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 1000, interval);
        return timer;
    }
}
